﻿
using Opc.Ua;
using Opc.Ua.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace hconnect {
    public class OPCTcpDMConnect :OPCTcpConnect {
        bool isAddSubscription = false;

        public T ReadNode<T>(string tag) {
            DataValue dataValue = ReadNode(new NodeId("ns=3;s=" + tag));
            return ( T ) dataValue.Value;
        }
        public object readNode(string tag) {
            DataValue dataValue = ReadNode(new NodeId("ns=3;s=" + tag));
            if( dataValue == null ) {
                return null;
            }
            return dataValue.Value;
        }
        private List<object> ReadNode(String[] keys) {
            List<object> list = new List<object>();
            try {
                // 添加所有的读取的节点，此处的示例是类型不一致的情况
                List<NodeId> nodeIds = new List<NodeId>();
                foreach( String key in keys ) {
                    nodeIds.Add(new NodeId("ns=3;s=" + key));
                }
                // dataValues按顺序定义的值，每个值里面需要重新判断类型
                List<DataValue> dataValues = ReadNodes(nodeIds.ToArray());
                // 然后遍历你的数据信息
                foreach( var dataValue in dataValues ) {
                    // 获取你的实际的数据
                    object value = dataValue.WrappedValue.Value;
                    list.Add(value);
                }
            } catch( Exception ex ) {
                forceDisConnection();
            }
            return list;
        }
        public void WriteNode(String key ,byte b) {
            WriteNode<byte>("ns=3;s=" + key ,b);
        }
        private void WriteNode(String[] keys ,object[] values) {
            for( int i = 0;i < keys.Length;i++ ) {
                keys[i] = "ns=3;s=" + keys[i];
            }
            try {
                // 此处演示写入一个short，2个float类型的数据批量写入操作
                bool success = WriteNodes(keys ,values);
                if( !success ) {
                    forceDisConnection();
                }
            } catch( Exception ex ) {
                forceDisConnection();
            }
        }
    }
}
